package com.hengpeng.itfin.domain.draw.common;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * <pre>
 * 提现专用
 * </pre>
 * @author shanguogang
 * @version 1.0, 2015-8-12
 */
public class FileCSVHelper
{
	private static Log logger = LogFactory.getLog(FileCSVHelper.class);

	private boolean convertFlag = false;

	public static final String DEL_CHAR = ",";

	public static final String AV_CHAR = "\"";

	private FileOutputStream fos = null;

	private StringBuffer sb = null;

	private InputStreamReader fr = null;

	/** *********************创建CSV文件***************************** */

	public void initGenerateCSVFile(String file)
	{
		try
		{
			fos = new FileOutputStream(file, false);
			sb = new StringBuffer();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	public String CSVEncode(String in)
	{
		if (in == null)
			return "";
		in.replaceAll("&", "&amp;");
		in.replaceAll("\"", "&quot;");
		return in;
	}

	public String CSVDecode(String in)
	{
		if (in == null)
			return "";
		in.replaceAll("&quot;", "\"");
		in.replaceAll("&amp;", "&");
		return in;
	}

	public void setData(String data)
	{
		if (convertFlag)
			data = CSVEncode(data);
		sb.append(AV_CHAR);
		sb.append(data);
		sb.append(AV_CHAR);
		sb.append(DEL_CHAR);
	}

	public void setConvertFlag(boolean b)
	{
		convertFlag = b;
	}

	public void writeLine()
	{
		if (sb.charAt(sb.length() - 1) == ',')
			sb.delete(sb.length() - 1, sb.length());
		sb.append("\r\n");
	}

	public void writeDataByLine(String[] args)
	{
		for (int i = 0; i < args.length; i++)
			setData(args[i]);
		writeLine();
	}

	public void close() throws IOException
	{
		try
		{
			if (fos != null)
				fos.write(sb.toString().getBytes());
		}
		catch (IOException e)
		{
			throw e;
		}
		finally
		{
			if (fos != null)
				fos.close();
			if (fr != null)
				fr.close();
		}
	}

	/** *********************解析CSV文件***************************** */
	public void initAnalyzeCSVFile(String file) throws IOException
	{
		fr = new InputStreamReader(new FileInputStream(file));
	}

	/** *********************通常的做法***************************** */
	/**
	 * 将data写入file
	 */
	public static boolean generateCSVFile(String file, String data)
	{
		boolean success = true;
		
		OutputStream fos=null;
		OutputStreamWriter osw=null;
		FileWriter fw = null;
		try
		{
			fos=new FileOutputStream(new File(file),false);
			osw=new OutputStreamWriter(fos,"gbk");
			BufferedWriter bw = new BufferedWriter(osw);
			bw.write(data);
			bw.flush();
		}
		catch (IOException e)
		{
			e.printStackTrace();
			logger.error(e);
			success = false;
		}
		finally
		{
			try
			{
				if (fw != null)
					fw.close();
			}
			catch (IOException e)
			{
				e.printStackTrace();
				logger.error(e);
			}
		}
		return success;
	}

	public static String loadCSVFile(String file)
	{
		StringBuffer content = new StringBuffer();
		BufferedReader br = null;
		try
		{
			br = new BufferedReader(new FileReader(file));
			String line = br.readLine();
			while (line != null)
			{
				content.append(line);
				line = br.readLine();
			}
		}
		catch (FileNotFoundException fe)
		{
			logger.error(fe);
		}
		catch (IOException ioe)
		{
			logger.error(ioe);
		}
		finally
		{
			try
			{
				if (br != null)
					br.close();
			}
			catch (IOException ex)
			{
				logger.error(ex);
			}
		}
		return content.toString();
	}

	public void analyzeCSVFile(String file)
	{
		InputStreamReader fr = null;
		BufferedReader br = null;
		try
		{
			fr = new InputStreamReader(new FileInputStream(file));
			br = new BufferedReader(fr);
			String rec = null;
			String[] argsArr = null;
			while ((rec = br.readLine()) != null)
			{
				System.out.println(rec);
				argsArr = rec.split(",");
				for (int i = 0; i < argsArr.length; i++)
				{
					System.out.println("seq " + (i + 1) + ":" + argsArr[i]);
				}
			}
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if (fr != null)
					fr.close();
				if (br != null)
					br.close();
			}
			catch (IOException ex)
			{
				ex.printStackTrace();
			}
		}
	}

	public synchronized static void logUploadedFileName(String logContent, String uploadLog, boolean append, String msg)
			throws IOException
	{
		FileWriter fw = null;
		try
		{
			fw = new FileWriter(uploadLog, append);
			if (logContent != null)
			{
				if (!logContent.endsWith("\r\n"))
				{
					logContent += "\r\n";
				}
				fw.write(logContent);
				logger.info(msg);
			}
		}
		finally
		{
			try
			{
				if (fw != null)
				{
					fw.close();
					fw = null;
				}
			}
			catch (IOException ex)
			{
				ex.printStackTrace();
			}
		}
	}

	public synchronized static boolean checkFileNameInUploaded(String csv, String uploadLog) throws IOException
	{

		List<String> csvList = getFileNamesUploaded(uploadLog);
		StringBuffer buf = new StringBuffer();
		for (String csvname : csvList)
		{
			buf.append(csvname).append("\r\n");
		}
		return csvList.contains(csv);

	}

	public synchronized static void delUploadedFileName(String csv, String uploadLog) throws IOException
	{
		List<String> csvList = getFileNamesUploaded(uploadLog);
		csvList.remove(csv);
		StringBuffer buf = new StringBuffer();
		for (String csvname : csvList)
		{
			buf.append(csvname).append("\r\n");
		}
		logUploadedFileName(buf.toString(), uploadLog, false, "从[" + uploadLog + "]文件中移除上传记录 [" + csv + "]");
	}

	/**
	 * 处理结果写入dbErrLog.txt
	 * @param downloadPayBean
	 * @param dbErrLog
	 * @param append
	 * @param msg
	 */
	/*
	 * public static void logDbErr(DownloadPayBean downloadPayBean, String dbErrLog, boolean append, String msg) {
	 * String logContent = "Date:" + PayUtil.getCurrDate() + "   AutoId:" + downloadPayBean.getAutoId() +
	 * "   Alipay return status:" + downloadPayBean.getStatus() + "   Database return result:" +
	 * downloadPayBean.getRetstr(); try { logUploadedFileName(logContent, dbErrLog, append, msg); } catch (Exception ex)
	 * { logger.info("when log database return result [" + logContent + "], error occurs,please check it!");
	 * logger.error(ex); } }
	 */

	public static String getFileNameUploaded(String uploadLog) throws IOException
	{
		String cvsfilename = null;
		BufferedReader br = null;
		StringBuffer buf = new StringBuffer();
		try
		{
			br = new BufferedReader(new FileReader(uploadLog));
			cvsfilename = br.readLine();// 读取首行,然后从文件里删除该行
			if (cvsfilename != null && cvsfilename.trim().length() > 0 && !cvsfilename.equals("\r\n"))
			{
				String cvs;
				while ((cvs = br.readLine()) != null)
				{
					buf.append(cvs).append("\r\n");
				}
				logUploadedFileName(buf.toString(), uploadLog, false, "pop cvs-file-name [" + cvsfilename
						+ "] being download from " + uploadLog);
			}
			else
			{
				cvsfilename = null;
			}
		}
		finally
		{
			try
			{
				if (br != null)
					br.close();
			}
			catch (IOException ex)
			{
				ex.printStackTrace();
			}
		}
		return cvsfilename;
	}

	/**
	 * 获取uplodeLog.txt中的上传文件名
	 * @param uploadLog
	 * @return
	 * @throws IOException
	 */
	public static List<String> getFileNamesUploaded(String uploadLogtxt) throws IOException
	{
		List<String> csvList = new ArrayList<String>();
		BufferedReader br = null;
		try
		{
			br = new BufferedReader(new FileReader(uploadLogtxt));
			String cvs;
			StringBuffer buf = new StringBuffer();
			while ((cvs = br.readLine()) != null)
			{
				if (cvs.trim().length() > 0 && !cvs.equals("\r\n"))
				{
					csvList.add(cvs);
					buf.append(cvs).append(",");
				}
			}
		}
		finally
		{
			try
			{
				if (br != null)
				{
					br.close();
					br = null;
				}
			}
			catch (IOException ex)
			{
				ex.printStackTrace();
			}
		}
		return csvList;
	}

	/**
	 * <pre>
	 * 检查路径是否存在,如果不存在则创建该路径
	 * </pre>
	 * @param path
	 * @throws Exception
	 */
	public static String checkPath(String path) throws Exception
	{
		boolean flag = true;
		File f = new File(path);
		if (f.isAbsolute())
		{
			if (!f.exists())
			{
				flag = f.mkdirs();
				if (!flag)
				{
					throw new Exception("创建路径失败!!");
				}
			}
		}
		else
		{
			throw new Exception("路径不是 绝对路径,不能创建");
		}
		return path;
	}

	public static void main(String[] args)
	{
		String path = "e:/te/memberstore/1001/download/";
		try
		{
			System.out.println(checkPath(path));
		}
		catch (Exception e1)
		{
			e1.printStackTrace();
		}
		try
		{
			// System.out.println("abc.sdfs".indexOf("sefs.sdfs"));
			// FileCSVHelper.getFileNamesUploaded("e:\\upload.txt").size();
			// FileCSVHelper.logUploadedFileName("aaa","e:\\upload.txt",true,"将aaa写入文件upload.txt");
			if (false)
			{
				FileCSVHelper csvCre = new FileCSVHelper();
				csvCre.initGenerateCSVFile("e:\\test.csv");
				csvCre.setConvertFlag(true);
				csvCre.setData("aaa");
				csvCre.setData("aa,a");
				csvCre.writeLine();
				csvCre.setData("aa\"a");
				csvCre.setData("aa,a");
				csvCre.setData("aa,a");
				csvCre.writeLine();
				csvCre.setData("aa\"a");
				csvCre.setData("aa,\"a");
				csvCre.setData("aa,\"a");
				csvCre.setData("aa,\"a");
				csvCre.setData("aa,\"a");
				csvCre.writeLine();
				csvCre.close();
			}
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}

		try
		{
			if (false)
			{
				FileCSVHelper csvAna = new FileCSVHelper();
				csvAna.setConvertFlag(true);
				/*
				 * ArrayList al = csvAna.analysisLine(); for (int i = 0; i < al.size(); i++) { ArrayList al1 =
				 * (ArrayList) al.get(i); for (int j = 0; j < al1.size(); j++) { System.out.println(al1.get(j)); } }
				 */
				csvAna.close();
			}
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}

	}

}
